package database.service;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Iterator;

import database.auxiliary.LogGenerator;

import po.OrderPO;

public class OrderDataServiceSerializableImpl implements OrderDataService {

	private ArrayList<OrderPO> orderList;
	
	public OrderDataServiceSerializableImpl() {
		orderList = new ArrayList<OrderPO>();
	}

	@Override
	public void load() {
		try {
			File file = new File("data/order.ser");
			if (!file.exists()) {
				file.createNewFile();
			}
			ObjectInputStream oiStream = new ObjectInputStream(
					new FileInputStream(file));
			OrderPO orderPO;
			while ((orderPO = (OrderPO) oiStream.readObject()) != null) {
				orderList.add(orderPO);
			}
			LogGenerator.log("Order data load succeed");
		} catch (EOFException e) {
			save();
			load();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void save() {
		try {
			FileOutputStream fos = new FileOutputStream("data/order.ser");
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			for (int i = 0; i < orderList.size(); i++) {
				oos.writeObject(orderList.get(i));
			}
			oos.writeObject(null);
			oos.close();
			LogGenerator.log("sale data save succeed!");
		} catch (FileNotFoundException e) {
			System.out.println("File found failed!");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public int insert(OrderPO order) {
		order.setId(orderList.size() + 1);
		orderList.add(order);
		LogGenerator.log("Order insert: " + order.toString());
		return orderList.size();
	}

	@Override
	public void delete(OrderPO order) {
		for (int i = 0; i < orderList.size(); i++) {
			if (orderList.get(i).getId() == order.getId()) {
				orderList.get(i).setId(-orderList.get(i).getId());
				LogGenerator.log("Order delete: " + order);
			}
		}
	}

	@Override
	public void update(OrderPO order) {
		for (int i = 0; i < orderList.size(); i++) {
			if (order.getId() == orderList.get(i).getId()) {
				orderList.set(i, order);
				LogGenerator.log("Order update: " + order);
			}
		}
	}

	@Override
	public OrderPO find(int id) {
		for (int i = 0; i < orderList.size(); i++) {
			if (id == orderList.get(i).getId()) {
				LogGenerator.log("Order find: " + orderList.get(i));
				return new OrderPO(orderList.get(i));
			}
		}
		return null;
	}

	@Override
	public Iterator<OrderPO> getIterator() {
		LogGenerator.log("Order return itr, length = " + orderList.size());
		return orderList.iterator();
	}
}
